<template>
  <div class="system-config-management">
    <div class="page-header">
      <div class="header-left">
        <h2>系统配置管理</h2>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="showCreateDialog">
          <el-icon><Plus /></el-icon>新建配置
        </el-button>
      </div>
    </div>

    <!-- 系统配置列表 -->
    <div class="table-container">
      <el-table
        v-loading="loading.configs"
        :data="configs"
        border
        style="width: 100%"
      >
        <el-table-column prop="key" label="配置键" min-width="150" />
        <el-table-column prop="value" label="配置值" min-width="200" />
        <!-- <el-table-column prop="type" label="数据类型" width="120">
          <template #default="{ row }">
            <el-tag>{{ row.type }}</el-tag>
          </template>
        </el-table-column> -->
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button-group class="operation-buttons">
              <el-button type="primary" @click="showEditDialog(row)">
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-button type="danger" @click="handleDelete(row)">
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 创建/编辑配置对话框 -->
    <el-dialog
      v-model="dialogs.config"
      :title="editingConfig.id ? '编辑配置' : '新建配置'"
      width="550px"
    >
      <el-form
        ref="configFormRef"
        :model="editingConfig"
        :rules="configRules"
        label-width="100px"
      >
        <el-form-item label="配置键" prop="key">
          <el-input v-model="editingConfig.key" placeholder="请输入配置键" :disabled="!!editingConfig.id" />
        </el-form-item>
        <el-form-item label="数据类型" prop="type">
          <el-select v-model="editingConfig.type" placeholder="请选择数据类型" style="width: 100%">
            <el-option label="字符串" value="string" />
            <el-option label="数字" value="number" />
            <el-option label="布尔值" value="boolean" />
            <el-option label="JSON" value="json" />
          </el-select>
        </el-form-item>
        <el-form-item label="配置值" prop="value">
          <el-input 
            v-if="editingConfig.type !== 'boolean'" 
            v-model="editingConfig.value" 
            :type="editingConfig.type === 'json' ? 'textarea' : 'text'" 
            :rows="editingConfig.type === 'json' ? 5 : 1"
            placeholder="请输入配置值" 
          />
          <el-switch
            v-else
            v-model="editingConfig.boolValue"
            active-text="true"
            inactive-text="false"
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="editingConfig.description" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogs.config = false">取消</el-button>
          <el-button type="primary" :loading="loading.submit" @click="handleSubmitConfig">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, watch, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, Edit, Delete
} from '@element-plus/icons-vue'
import { 
  getSystemConfigList, 
  createSystemConfig, 
  updateSystemConfig, 
  deleteSystemConfig
} from '@/api/config'

// 状态变量
const configs = ref([])
const editingConfig = ref({
  key: '',
  value: '',
  boolValue: false,
  type: 'string',
  description: ''
})

// 加载状态
const loading = reactive({
  configs: false,
  submit: false
})

// 对话框显示状态
const dialogs = reactive({
  config: false
})

// 表单引用
const configFormRef = ref(null)

// 表单验证规则
const configRules = {
  key: [
    { required: true, message: '请输入配置键', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_\.]+$/, message: '配置键只能包含字母、数字、下划线和点', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择数据类型', trigger: 'change' }
  ],
  value: [
    { required: true, message: '请输入配置值', trigger: 'blur' }
  ]
}

// 初始化
onMounted(() => {
  fetchConfigList()
})

// 获取配置列表
const fetchConfigList = async () => {
  try {
    loading.configs = true
    
    const data = await getSystemConfigList()

    configs.value = Array.isArray(data.items) ? data.items : []
  } catch (error) {
    console.error('获取系统配置失败:', error)
    ElMessage.error('获取系统配置失败')
  } finally {
    loading.configs = false
  }
}

// 显示创建对话框
const showCreateDialog = () => {
  editingConfig.value = {
    key: '',
    value: '',
    boolValue: false,
    type: 'string',
    description: ''
  }
  dialogs.config = true
}

// 显示编辑对话框
const showEditDialog = (config) => {
  editingConfig.value = { ...config }
  
  // 如果是布尔类型，设置boolValue
  if (config.type === 'boolean') {
    editingConfig.value.boolValue = config.value.toLowerCase() === 'true'
  }
  
  dialogs.config = true
}

// 监控类型变化，处理值的转换
watch(() => editingConfig.value.type, (newType, oldType) => {
  const config = editingConfig.value
  
  if (newType === 'boolean') {
    // 转换为布尔值表示
    config.boolValue = config.value === 'true'
  } else if (oldType === 'boolean') {
    // 从布尔值转换为字符串
    config.value = config.boolValue.toString()
  } else if (newType === 'number' && oldType !== 'number') {
    // 尝试转换为数字
    const num = parseFloat(config.value)
    if (!isNaN(num)) {
      config.value = num.toString()
    } else {
      config.value = '0'
    }
  }
})

// 监控布尔值变化
watch(() => editingConfig.value.boolValue, (newVal) => {
  if (editingConfig.value.type === 'boolean') {
    editingConfig.value.value = newVal.toString()
  }
})

// 提交配置表单
const handleSubmitConfig = async () => {
  try {
    await configFormRef.value.validate()
    
    loading.submit = true
    
    // 准备提交数据
    const submitData = { ...editingConfig.value }
    delete submitData.boolValue
    
    // 处理类型转换
    if (submitData.type === 'number') {
      submitData.value = parseFloat(submitData.value)
      if (isNaN(submitData.value)) {
        submitData.value = 0
      }
    } else if (submitData.type === 'boolean') {
      submitData.value = submitData.value === 'true'
    } else if (submitData.type === 'json') {
      try {
        // 验证JSON格式
        JSON.parse(submitData.value)
      } catch (e) {
        ElMessage.error('JSON格式错误: ' + e.message)
        loading.submit = false
        return
      }
    }
    
    if (editingConfig.value.id) {
      // 更新现有配置
      await updateSystemConfig(editingConfig.value.id, submitData)
      ElMessage.success('配置更新成功')
    } else {
      // 创建新配置
      await createSystemConfig(submitData)
      ElMessage.success('配置创建成功')
    }
    
    dialogs.config = false
    fetchConfigList()
  } catch (error) {
    console.error('保存配置失败:', error)
    ElMessage.error('保存配置失败: ' + (error.response?.data?.detail || error.message))
  } finally {
    loading.submit = false
  }
}

// 删除配置
const handleDelete = async (config) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除配置 "${config.key}" 吗？此操作不可恢复。`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteSystemConfig(config.id)
    ElMessage.success('配置删除成功')
    fetchConfigList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除配置失败:', error)
      ElMessage.error('删除配置失败: ' + (error.response?.data?.detail || error.message))
    }
  }
}
</script>

<style scoped>
.system-config-management {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left h2 {
  margin: 0;
}

.header-right {
  display: flex;
  gap: 10px;
}

.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: auto;
}

.operation-buttons {
  display: flex;
  flex-wrap: nowrap;
}
</style> 